#include"../include/head.h"
int client_ls(ResponsePackage *presponse,ClientVirtualPathStack* pvirtualpathstack){
    printf("client_ls= %s\n", presponse->args_val);
    return 0;
}


int client_pwd(ResponsePackage *presponse,ClientVirtualPathStack* pvirtualpathstack){
   
    char str[1024];
    ClientVirtualPathStack_print(pvirtualpathstack, str);
    printf("%s\n", str);
    return 0;
}
int client_mkdir(ResponsePackage *presponse,ClientVirtualPathStack* pvirtualpathstack){
    printf("%s\n", presponse->args_val);
    return 0;
}
int client_rmdir(ResponsePackage *presponse,ClientVirtualPathStack* pvirtualpathstack){
    printf("%s\n", presponse->args_val);
    return 0;
}

int client_cd(ResponsePackage *presponse,ClientVirtualPathStack* pvirtualpathstack) {
    char vir_path[1024] = {0};
    memcpy(vir_path, presponse->vir_path_val, presponse->vir_path_len);
    // 将链栈全部弹栈，重新放入新的路径
    while (pvirtualpathstack->size != 0)
    {
        ClientVirtualPathStack_pop(pvirtualpathstack);
    }

    pathTostack(pvirtualpathstack, vir_path);
    memcpy(vir_path, presponse->vir_path_val, presponse->vir_path_len);
    if(strlen(vir_path) == 0) {
        snprintf(vir_path, sizeof(vir_path), "/");
    }
    fprintf(stdout, "成功转到目标路径: %s \n", vir_path);

    return 0;
}

int pathTostack(ClientVirtualPathStack *pstack, char *path) {
    // 虚拟工作路径是/dir1/dir2，拆分使用/作为分界
    // 参数路径是dir3/../dir4/../dir5
    char *token;     // 切割出来的字符串
    char *saveptr;  // 保存切割完后的剩余字符串
    // 必须要考虑到path是空字符串，如何处理
    for(char *str = path; ; str = NULL) {
        token = strtok_r(str, "/", &saveptr);
        if(token == NULL) break;
        else if(strcmp(token, ".") == 0) {
            continue;
        } else if(strcmp(token, "..") == 0) {
            if(pstack->size == 0) {
                continue;
            } else {
                ClientVirtualPathStack_pop(pstack);
            }
        } else {
            // printf("before push \n");
            ClientVirtualPathStack_push(pstack, token);
            // printf("after push \n");
        }
    }

    return 0;
}
